package com.imis.module.base;

import com.imis.module.system.model.po.SysLog;
import com.imis.module.system.model.vo.SysUserVO;
import com.imis.module.system.service.ISysLogService;
import com.imis.base.util.CurrentUserUtils;
import com.imis.base.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;

/**
 * <p>
 * 通用 业务处理类
 * </p>
 *
 * @author XinLau
 * @since 2020-03-27
 */
@Slf4j
public abstract class BaseBus {

    @Autowired
    protected ISysLogService sysLogService;

    /**
     * Redis 工具类
     */
    @Autowired
    protected RedisUtil redisUtil;

    /**
     * 保存日志
     * @param logContent - 内容
     * @param logType - 日志类型(CommonConstant.LOG_TYPE_x)
     * @param operateType - 操作类型(CommonConstant.OPERATE_TYPE_x)
     * @author XinLau
     * @since 2020/3/13 11:36
     * @creed The only constant is change ! ! !
     */
    private void addLog(String logContent, Integer logType, Integer operateType){
//        1.创建日志对象，初始化传入的参数
        SysLog sysLog = new SysLog();
        sysLog.setLogContent(logContent);
        sysLog.setLogType(logType);
        sysLog.setOperateType(operateType);
        sysLog.setCreateTime(LocalDateTime.now());

////        2.请求的方法名
//        sysLog.setMethod(CommonConstant.EMPTY);
////        3.请求的参数
//        sysLog.setRequestParam(CommonConstant.EMPTY);
////        4.请求类型
//        sysLog.setRequestType(CommonConstant.EMPTY);

//        5.设置IP地址
        try {
            sysLog.setIp(CurrentUserUtils.getUserIp());
        } catch (Exception e) {
            sysLog.setIp("127.0.0.1");
        }
//        6.获取登录用户信息
        SysUserVO sysUser = CurrentUserUtils.getLoginUser();
        if(sysUser != null){
            sysLog.setUserId(sysUser.getId());
            sysLog.setUsername(sysUser.getUsername());
        }
//        7.保存系统日志
        sysLogService.save(sysLog);
    }

    /**
     * 保存日志
     * @param logType - 日志类型(CommonConstant.LOG_TYPE_x)
     * @param operateType - 操作类型(CommonConstant.OPERATE_TYPE_x)
     * @param logContentFormat - 内容带占位符
     * @param args - 占位符参数
     * @author XinLau
     * @since 2020/3/13 11:36
     * @creed The only constant is change ! ! !
     */
    public void addLog(Integer logType, Integer operateType, String logContentFormat, Object ... args){
        logContentFormat = String.format(logContentFormat, args);
        addLog(logContentFormat, logType, operateType);
    }

}
